<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * @author Amitav Roy
 *
 * This library is a copy of the drupal boost module. 
 * It will try to mimic the module which will first check if the page
 * has a static version - a flat file or not. 
 * If the cache version is found, then the file will be server and no DB connection 
 * will be required.
 *
 * If this is not present, or expired then the page will get build.
 */

class Boost {
	private $CI; // CodeIgniter instance.
	private $cache_time = 604800; // a week
	private $target_folder = 'application/cache/';

	/**
	 * Calling the constructor.
	 */
	public function __construct() {
		$this->CI =& get_instance();
		$this->CI->load->helper('file');
	}

	private function folder_and_file_from_url() {
		// this is where the folders for cache will be created.

		// getting the folders that needs to be created.
		$url_to_folder = explode('/', uri_string());

		// getting the file name
		$filename = $url_to_folder[count($url_to_folder) - 1];
		array_pop($url_to_folder);

		// the final folder where cache will be stored
		$final_folder_string = $this->target_folder . implode('/', $url_to_folder);
		
		return array(
			'folder' => $final_folder_string,
			'file' => $filename
		);
	}

	public function get_boost_cache() {

		$file_folder = $this->folder_and_file_from_url();

		if (!$file_folder['file']) {
			// this is home page cache
			$file_folder['file'] = 'index';
		}

		if (get_file_info($file_folder['folder'] . '/' . $file_folder['file'] . '.html')) {
			$output = read_file($file_folder['folder'] . '/' . $file_folder['file'] . '.html');
			$this->CI->output->set_output($output);
			$this->CI->output->set_header("Boost-Cache: HIT");
			return true;
		}
		else {
			return false;
		}

	}

	public function set_boost_cache($data) {

		$file_folder = $this->folder_and_file_from_url();
		if (!$file_folder['file']) {
			// this is home page cache
			$file_folder['file'] = 'index';
		}
		else {
			// creating the folder for the cache.
			if (!file_exists($file_folder['folder'])) {
				mkdir($file_folder['folder'], 0777, true);
			}
		}

		$write_file = write_file($this->target_folder . $file_folder['file'] . '.html', $data);

		$file = get_file_info($this->target_folder . $file_folder['file'] . '.html');

		$prev_file_path = $file['server_path'];

		if (@copy($file['server_path'], $file_folder['folder'] . '/' . $file_folder['file'] . '.html')) {
			unlink($file['server_path']);
		}

		$this->CI->output->set_output($data);

	}
}